<?php

namespace app\admin\controller\ykjp\sell;

use app\common\controller\Backend;
use think\Db;

/**
 *
 *
 * @icon fa fa-circle-o
 */
class Sellreturn extends Backend {

    /**
     * Sellreturn模型对象
     * @var \app\admin\model\sell\Sellreturn
     */
    protected $model = null;

    public function _initialize() {
        parent::_initialize();
        $this->model = new \app\admin\model\ykjp\sell\Sellreturn;
        $this->view->assign("statusListList", $this->model->getStatusListList());
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 添加销售退货单
     */
    public function add() {

        if ($this->request->isAjax()) {
            $obj = $this->request->param("obj");
            //添加 销售出库单
            if ($obj == 5) {
                $row = $this->request->param("row/a"); //获取出库单总表数据
                $pdct = $this->request->param("product/a"); //获取出库单副表数据

                $firmid = $this->auth->firmid; //企业ID
                $admin = $this->auth->id; //当前登陆用户ID
                //数据验证
                $purchase = "";
                $pdct[0] = isset($pdct[0]) ? $pdct[0] : "";
                if ($pdct[0] == "") {
                    $this->error(__('Please add item'));
                }
                // 数据格式转换
                $all = json_decode($pdct[0]);
                $tep = $this->model->object_array($all);

                //处理要提交的数据
                $current_time = time(); //当前时间
                $row['createtime'] = $current_time; //创建时间
                $row['updatetime'] = $current_time; //更新时间
                $row['billing_time'] = strtotime($row['billing_time']); //制单时间
                $row['firmid'] = $this->auth->firmid; //企业ID
                $row['admin_id'] = $this->auth->id;
                $row['code'] = (isset($row['code']) && $row['code'] != "") ? $row['code'] : "YK" . date("ymdHis", time()) . rand(1000, 9999);
                $allMoney = 0;  //退款金额

                for ($i = 0; $i < count($tep); $i++) {
                    $allMoney = $allMoney + $tep[$i]['subtotal'];
                }
                $row['allMoney'] = $allMoney;
                $row['status_list'] = '1';  //状态（待审核）


                $sell_id = $row['sell_id'];  //销售单ID
                //提交数据（插入销售出库单主表->插入副表并更新关联的wp表（循环修改））
                // 启动事务
                Db::startTrans();
                try {
                    // 修改销售单状态为发起退货
                    Db::name('ykjp_sell')->where('id', $sell_id)->where('firmid', $this->auth->firmid)->update(['status_list' => 8]);

                    //插入销售退货单主表
                    Db::name('ykjp_sell_return')->insert($row);
                    $return_id = Db::name('ykjp_sell_return')->getLastInsID(); //获取刚插入数据的ID
                    //插入副表
                    for ($i = 0; $i < count($tep); $i++) {

                        $tep[$i]['createtime'] = $current_time;  //设置创建时间
                        $tep[$i]['updatetime'] = $current_time;  //设置更新时间
                        $tep[$i]['sell_return_id'] = $return_id;  //设置主表ID
                        $tep[$i]['firmid'] = $this->auth->firmid;  //企业ID

                        Db::name('ykjp_sell_return_p')->insert($tep[$i]); //插入副表
                    }

                    // 提交事务
                    Db::commit();
                    $this->success("提交成功", null, array("result" => "success", "url" => url("sell/sellreturn/index")));
                } catch (PDOException $e) {

                    Db::rollback();
                    $this->error('提交失败');
                } catch (Exception $e) {

                    Db::rollback();
                    $this->error('提交失败');
                }
                $this->error('提交失败');
            }
        }
        $date = date("Y-m-d", time());
        $this->assign("date", $date);
        return $this->view->fetch();
    }

    /**
     * 获取客户列表
     */
    public function getCList() {
        $this->model = new \app\admin\model\ykjp\information\basisinfo\Customerinfo;
        list($where, $sort, $order, $offset, $limit) = $this->buildparams();
        $total = $this->model
                ->where($where)
                // ->where('status', '正常')
                ->where('firmid', $this->auth->firmid)
                ->order($sort, $order)
                ->field("name,contact,phone,description,id")
                ->count();
        $list = $this->model
                ->where($where)
                // ->where('status', '正常')
                ->where('firmid', $this->auth->firmid)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->field("name,contact,phone,description,id,status")
                ->select();
        // halt($this->model->getLastSql());
        $list = collection($list)->toArray();
        $result = array("total" => $total, "rows" => $list);
        return json($result);
    }

    /**
     * 获取销售单列表
     */
    public function getSellList() {
        $supid = $this->request->param("supid");
        $this->model = new \app\admin\model\ykjp\sell\Sell;
        $this->searchFields = "code";
        list($where, $sort, $order, $offset, $limit) = $this->buildparams();
        $total = $this->model
                ->where($where)
                ->where("customer_info_id", $supid)
                ->where("status_list", 6)
                ->order($sort, $order)
                ->count();
        $list = $this->model
                ->where("customer_info_id", $supid)
                ->where($where)
                ->where("status_list", 6)
                ->order($sort, $order)
                ->select();
        $result = array("total" => $total, "rows" => $list);
        return json($result);
    }

    /**
     * 获取仓库信息
     */
    public function getWarehouse() {
        if ($this->request->isAjax()) {
            $type = $this->request->param("type");
            if ($type) {
                $hosemModel = new \app\admin\model\ykjp\information\basisinfo\Warehouse;
                $row = $hosemModel->where("firmid", $this->auth->firmid)->field('id as value,name')->order('id desc')->select();
                if ($row) {
                    $this->success('', null, $row);
                }
                $this->error(__('fail'));
            } else {
                $pid = $this->request->param("pid");
                $partModel = new \app\admin\model\ykjp\information\basisinfo\Partition;
                $row = $partModel->where("warehouse_id", $pid)->where("firmid", $this->auth->firmid)->field('id as value,name')->order('id desc')->select();
                if ($row) {
                    $this->success('', null, $row);
                }
                $this->error(__('fail'));
            }
        }
        $this->error(__('fail'));
    }

    /**
     * 详情
     */
    public function detail() {
        $ids = $this->request->param("ids");
        if ($ids == "") {
            $this->error("fail", "ykjp/sell/Sellreturn/index");
        }
        list($where, $sort, $order, $offset, $limit) = $this->buildparams();
        $list = Db::name('ykjp_sell_return')
                ->where($where)
                ->where('firmid', $this->auth->firmid)
                ->where("id", $ids)
                ->select();

        $dModel = new \app\admin\model\ykjp\sell\returnPro;
        $strProduct = $dModel->with(['products'])->where("sell_return_id", $ids)->where('products.firmid', $this->auth->firmid)->select();
        // halt($strProduct);

        $this->assign("detail", $list);
        $this->assign("product", $strProduct);
        return $this->view->fetch();
    }

    /**
     * 编辑销售退货单
     */
    public function edit($ids = null) {

        if ($this->request->isAjax()) {
            $product = $this->request->param("product/a");
            $row = $this->request->param("row/a");
            $ids = $row['ids'];  //退货单ID
            if ($ids == null) {
                $this->error(__('fail'));
            }

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $row['billing_time'] = strtotime($row['billing_time']);  //制单日期
            $row['updatetime'] = time();  //更新时间
            $row['code'] = (isset($row['code']) && $row['code'] != "") ? $row['code'] : "YK" . date("ymdHis", time()) . rand(1000, 9999);
            //更新销售退货单主表
            $dataRow = $this->model
                    ->where("id", $ids)
                    ->update([
                'linkman' => $row['linkman'],
                'phone' => $row['phone'],
                'billing_time' => $row['billing_time'],
                'warehouse_id' => $row['warehouse_id'],
                'partition_id' => isset($row['partition_id']) ? $row['partition_id'] : "",
                'city' => $row['city'],
                'address' => $row['address'],
                'remark' => $row['remark'],
                'totalNums' => $row['totalnums'],
                'allMoney' => $row['allMoney'],
                'updatetime' => time(),
                'code' => $row['code']
            ]);

            if (!$product) {
                $this->error(__('Product cannot be empty'));
            }
            $product = json_decode($product[0]);
            $product = $this->model->object_array($product);

            //销售副表
            $sellProduct = new \app\admin\model\ykjp\sell\returnPro;
            $where = [];
            foreach ($product as $key => $val) {
                $id = $val['data_id'];
                unset($val["data_id"]);
                $val['updatetime'] = time();
                if ($id) {
                    $up = $sellProduct->where("id", $id)->where('firmid', $this->auth->firmid)->update($val);
                    $where[] = $id;
                } else {
                    $val['sell_id'] = $ids;
                    $val['createtime'] = time();
                    $val['firmid'] = $this->auth->firmid;
                    $inser = $sellProduct->insertGetId($val);
                    if ($inser) {
                        $where[] = $inser;
                    }
                }
            }
            $deletTime['deletetime'] = time();
            $update = $sellProduct->where("sell_return_id", $ids)->where("id", "not in", $where)->update($deletTime);
            if ($update) {
                $this->success(null, null, ['result' => "success"]);
            }
            $this->success(null, null, ['result' => "success"]);
        }
        list($where, $sort, $order, $offset, $limit) = $this->buildparams();

        $detail = $this->model
                ->where($where)
                ->where('firmid', $this->auth->firmid)
                ->order($sort, $order)
                ->where("id", $ids)
                ->where("status_list", 1)
                ->select();

        if (!$detail) {
            $this->error(__('not editable'));
        }
        $productModel = new \app\admin\model\ykjp\sell\returnPro;
        $product = $productModel->with(['products'])->where("sell_return_id", $ids)->select();

        $sell_id = $detail[0]['sell_id'];  //获取当前销售单的ID
        if ($product) {
            foreach ($product as $key => $value) {
                //处理规格
                $a = json_decode($value['products']['prop']);
                $value['products']['prop'] = $this->model->object_array($a);

                //根据当前销售单ID和商品ID查询销售数量
                $product_id = $value['products']['id'];
                $volume = Db::name('ykjp_sell_product')
                        ->field('nums')
                        ->where('firmid', $this->auth->firmid)
                        ->where('product_id', $product_id)
                        ->where('sell_id', $sell_id)
                        ->find();
                $value['products']['volume'] = $volume['nums'];
            }
        }

        $this->assign("detail", $detail);
        $this->assign("product", $product);
        return $this->view->fetch();
    }

    /**
     * 反审核
     */
    public function Anti($ids = null) {
        if ($ids) {
            $data = $this->model->where("firmid", $this->auth->firmid)->where("status_list", "in", [2, 3, 4])->where("id", $ids)->find();
            if ($data) {
                $updateData = array("updatetime" => time(), "status_list" => "1", "reason" => null, 'cause' => null);
                $up = $this->model->where("id", $ids)->update($updateData);
                if ($up) {
                    $this->success(null, null, array("result" => "success"));
                } else {
                    $this->error(__("operate fail"));
                }
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

    /**
     * 作废销售退货单
     */
    public function abandon() {
        $ids = $this->request->post('ids'); //要作废的销售出库单ID
        $reason = $this->request->post('reason'); //作废理由
        //获取销售单ID
        $sellRes = Db::name('ykjp_sell_return')
                ->field('sell_id')
                ->where('id', $ids)
                ->where('firmid', $this->auth->firmid)
                ->find();
        $sell_id = $sellRes['sell_id'];

        Db::startTrans();
        try {

            // 修改销售单状态为发起退货
            Db::name('ykjp_sell')->where('id', $sell_id)->where('firmid', $this->auth->firmid)->update(['status_list' => 7, 'updatetime' => time()]);

            // 修改销售退货单状态为已作废
            Db::name('ykjp_sell_return')->where('id', $ids)->where('firmid', $this->auth->firmid)->update(['status_list' => -1, 'updatetime' => time(), 'reason' => $reason]);

            // 提交事务
            Db::commit();
            $this->success("提交成功", null, array("result" => "success", "url" => url("ykjp/sell/sellreturn/index")));
        } catch (PDOException $e) {

            Db::rollback();
            $this->error('提交失败');
        } catch (Exception $e) {

            Db::rollback();
            $this->error('提交失败');
        }
        $this->error('提交失败');
    }

}
